package com.hankarun.gevrek;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.nntp.NNTPClient;
import org.apache.commons.net.nntp.NewsgroupInfo;

import com.hankarun.gevrek.lib.GevrekWidgetProvider;
import com.hankarun.gevrek.lib.NewsGroupName;
import com.hankarun.gevrek.lib.ServerManager;
import com.hankarun.gevrek.lib.ServerManager.MySSLSocketFactory;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.InputType;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class WidgetActivity extends Activity {
    public static final String PREFS_USERNAME_PATTERN = "Username-%d";
    public static final String PREFS_PASSWORD_PATTERN = "Password-%d";
    public static final String PREFS_NEWSGROUP_PATTERN = "Newsgroup-%d";
    public static final String PREFS_WIDGETNAME_PATTERN = "Widgetname-%d";
    public static final String PREFS_TIME_PATTERN = "Time-%d";
    public static final String PREFS_COUNT_PATTERN = "Count-%d";
    public static final String PREFS_COUNT1_PATTERN = "Count1-%d";
    
    public static final String UPDATE_WIDGET = "WIDGET_UPDATE";
	
	private Button nextButton;
	private ListView widgetlist;
	private String username;
	private String password;
	private String newsgroup;
	private String widgetname;
	private String time;
	private String search;
	private long count;
	protected ServerManager app;
	private List<NewsGroupName> newsgroups;		
	
	public static final String PREFS_NAME = "GevrekPrefs";
	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
	public ArrayList<NewsGroupName> getGroups(String _username, String _password){
		NNTPClient client = new NNTPClient();
		ArrayList<NewsGroupName> groups = new ArrayList<NewsGroupName>();
		try {
			client.setSocketFactory(new MySSLSocketFactory());
			client.connect("news.ceng.metu.edu.tr",563);
			if(!client.authenticate(_username, _password))
				return null;
			
			for(NewsgroupInfo n : client.iterateNewsgroups()) {
			    groups.add(new NewsGroupName(n.getNewsgroup(),n.getLastArticleLong()));
			}
			return groups;
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        username = settings.getString("username", "");
        password = settings.getString("password", "");
        newsgroup = "";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_widget);
        
        setResult(RESULT_CANCELED);
        
        app = (ServerManager)getApplication();
        
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        
        widgetlist = (ListView) findViewById(R.id.widgetlist);
        String[] contents = { getString(R.string.setusername),
        					getString(R.string.setpassowrd),
        					getString(R.string.selectnewsgroup),
        					getString(R.string.setwidgetname)};
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(WidgetActivity.this,
        		android.R.layout.simple_list_item_1, contents);
        widgetlist.setAdapter(adapter);
        
        widgetlist.setOnItemClickListener(new OnItemClickListener() {
    		@Override
    		public void onItemClick(AdapterView<?> parent, View view,
    			int position, long id) {
    			switch(position){
    				case 0:
    					final EditText input = new EditText(WidgetActivity.this);
    					input.setText(username);
    			        new AlertDialog.Builder(WidgetActivity.this)
    			            .setTitle(R.string.cowusername)
    			            .setMessage(R.string.enterusername)
    			            .setView(input)
    			            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    			                 public void onClick(DialogInterface dialog, int whichButton) {
    			                     username = input.getText().toString(); 
    			                 }
    			            })
    			            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
    			                 public void onClick(DialogInterface dialog, int whichButton) {
    			                 }
    			            }).show();    					
    					break;
    				case 1:
    					final EditText input1 = new EditText(WidgetActivity.this);
    					input1.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    					input1.setText(password);
    			        new AlertDialog.Builder(WidgetActivity.this)
    			            .setTitle(R.string.cowpassword)
    			            .setMessage(R.string.enterpassword)
    			            .setView(input1)
    			            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    			                 public void onClick(DialogInterface dialog, int whichButton) {
    			                     password = input1.getText().toString(); 
    			                 }
    			            })
    			            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
    			                 public void onClick(DialogInterface dialog, int whichButton) {
    			                 }
    			            }).show();      					
    					break;
    				case 2:
    					if(!username.equals("")&&!password.equals("")){
	    			        final EditText input2 = new EditText(WidgetActivity.this);
	
	    			        new AlertDialog.Builder(WidgetActivity.this)
	    			            .setTitle(R.string.searchingroups)
	    			            .setMessage(R.string.putsearchstirng)
	    			            .setView(input2)
	    			            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
	    			                 public void onClick(DialogInterface dialog, int whichButton) {
	    			                	 	search = input2.getText().toString();
	    			                     	ServerTask task = new ServerTask();
	    			                 		task.execute();
	    			                 }
	    			            })
	    			            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	    			                 public void onClick(DialogInterface dialog, int whichButton) {
	    			                 }
	    			            }).show();
    					}else{
    						if(!username.equals(""))
    							Toast.makeText(getApplicationContext(), R.string.setusernameplease, Toast.LENGTH_SHORT).show();
    						if(!password.equals(""))
    							Toast.makeText(getApplicationContext(), R.string.setpasswordplease, Toast.LENGTH_SHORT).show();
    					}

    					break;
    				case 3:
    					final EditText input3 = new EditText(WidgetActivity.this);
    					input3.setText(newsgroup);
    			        new AlertDialog.Builder(WidgetActivity.this)
    			            .setTitle(R.string.setwidgetname)
    			            .setMessage(R.string.enterwidgetname)
    			            .setView(input3)
    			            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    			                 public void onClick(DialogInterface dialog, int whichButton) {
    			                     widgetname = input3.getText().toString(); 
    			                 }
    			            })
    			            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
    			                 public void onClick(DialogInterface dialog, int whichButton) {
    			                 }
    			            }).show();    					
    					break;
    			}
    					
    			
    		}
    	});
        
        
        nextButton = (Button) findViewById(R.id.nextbutton);
        
        nextButton.setOnClickListener(new View.OnClickListener() 
        {         
        	public void onClick(View view)  
            {
        		if(!newsgroup.equals("")){
	        		final Context context = WidgetActivity.this;
	        		String[] var = {username,password,newsgroup,widgetname,time,String.valueOf(count)};
	
	        		setPref(context,mAppWidgetId,var);
	
	                // Make sure we pass back the original appWidgetId
	                Intent resultValue = new Intent();
	                resultValue.setAction(UPDATE_WIDGET);
	                resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
	                setResult(RESULT_OK, resultValue);
	                finish();
        		}else
        			Toast.makeText(getApplicationContext(), R.string.nonewsgroupselected, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public WidgetActivity() {
        super();
    }
    
    public static void setCount(Context context, int appWidgetId, String _count){
    	SharedPreferences.Editor prefs = context.getSharedPreferences("widgetGevrek", 0).edit();
    	prefs.putString(String.format(PREFS_COUNT_PATTERN, appWidgetId), _count);
    	prefs.commit();
    }
    
    public static String getPrefCount(Context context, int appWidgetId){
    	SharedPreferences prefs = context.getSharedPreferences("widgetGevrek", 0);
    	return prefs.getString(String.format(PREFS_COUNT1_PATTERN, appWidgetId), null);
    }
    
    public static void setPrefCount(Context context, int appWidgetId, String _count){
    	SharedPreferences.Editor prefs = context.getSharedPreferences("widgetGevrek", 0).edit();
    	prefs.putString(String.format(PREFS_COUNT1_PATTERN, appWidgetId), String.valueOf(_count));
    	prefs.commit();
    }
    
    public static void delPref(Context context, int appWidgetId){
    	SharedPreferences.Editor prefs = context.getSharedPreferences("widgetGevrek", 0).edit();
    	prefs.remove(String.format(PREFS_USERNAME_PATTERN, appWidgetId));
    	prefs.remove(String.format(PREFS_PASSWORD_PATTERN, appWidgetId));
    	prefs.remove(String.format(PREFS_NEWSGROUP_PATTERN, appWidgetId));
    	prefs.remove(String.format(PREFS_WIDGETNAME_PATTERN, appWidgetId));
    	prefs.remove(String.format(PREFS_TIME_PATTERN, appWidgetId));
    	prefs.remove(String.format(PREFS_COUNT_PATTERN, appWidgetId));
    	prefs.commit();    
    }
    
    public static void setPref(Context context, int appWidgetId, String[] var){
    	SharedPreferences.Editor prefs = context.getSharedPreferences("widgetGevrek", 0).edit();
        prefs.putString(String.format(PREFS_USERNAME_PATTERN, appWidgetId), var[0]);
        prefs.putString(String.format(PREFS_PASSWORD_PATTERN, appWidgetId), var[1]);
        prefs.putString(String.format(PREFS_NEWSGROUP_PATTERN, appWidgetId), var[2]);
        prefs.putString(String.format(PREFS_WIDGETNAME_PATTERN, appWidgetId), var[3]);
        prefs.putString(String.format(PREFS_TIME_PATTERN, appWidgetId), var[4]);
        prefs.putString(String.format(PREFS_COUNT_PATTERN, appWidgetId), var[5]);
        
        prefs.commit();
    }
    
    public static String[] loadPref(Context context, int appWidgetId) {
        SharedPreferences prefs = context.getSharedPreferences("widgetGevrek", 0);
        String things[] = new String[6];
        things[0] = prefs.getString(String.format(PREFS_USERNAME_PATTERN, appWidgetId), null);
        things[1] = prefs.getString(String.format(PREFS_PASSWORD_PATTERN, appWidgetId), null);
        things[2] = prefs.getString(String.format(PREFS_NEWSGROUP_PATTERN, appWidgetId), null);
        things[3] = prefs.getString(String.format(PREFS_WIDGETNAME_PATTERN, appWidgetId), null);
        things[4] = prefs.getString(String.format(PREFS_TIME_PATTERN, appWidgetId), null);
        things[5] = prefs.getString(String.format(PREFS_COUNT_PATTERN, appWidgetId), null);

        return things;
    }
    
    private class ServerTask extends AsyncTask<Void, Void, ArrayList<NewsGroupName>> {
    	private ProgressDialog dialog;
    	@Override
    	protected void onPreExecute(){
    		dialog = ProgressDialog.show(WidgetActivity.this, "", 
    				getString(R.string.downloadinggroups), true);
    	}
    	
    	@Override
    	protected void onPostExecute(ArrayList<NewsGroupName> s) {
    		if(s != null){
    			newsgroups = new ArrayList<NewsGroupName>();
	    	    dialog.dismiss();
		        //Select news group
	    	    for(NewsGroupName name : s)
	    	    	if(name.getGroup().contains(search)){
	    	    		newsgroups.add(name);
	    	    	}
	    	    final String[] items;
	    	    if(newsgroups.size()<1){
			        items = new String[s.size()];
			        for(int x = 0; x < s.size(); x++)
			        	items[x] = s.get(x).getGroup();
	    	    }else{
			        items = new String[newsgroups.size()];
			        for(int x = 0; x < newsgroups.size(); x++)
			        	items[x] = newsgroups.get(x).getGroup();
	    	    }
		        
		        AlertDialog.Builder builder = new AlertDialog.Builder(WidgetActivity.this);
		        builder.setTitle(R.string.selectnewsgroup);
		        builder.setItems(items, new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int item) {
		                newsgroup = items[item].toString();
		                count = newsgroups.get(item).getCount();
		            }
		        });
		        AlertDialog alert = builder.create();
		        alert.show();
    		}else{
    			Toast.makeText(getApplicationContext(), R.string.loginfailure, Toast.LENGTH_SHORT).show();
    			dialog.dismiss();
    		}
    	}

    	@Override
    	protected ArrayList<NewsGroupName> doInBackground(Void... params) {
			return getGroups(username,password);        	
    	}

    }
}
